<template>
  <a-modal
    :title="modalTitle"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    class="ant-modal2"
    @cancel="handleCancel"
  >
    <a-form :form="form">
      <row-list :col="1" v-show="false">
        <row-item>
          <a-form-item>
            <a-input v-decorator="['id']" type="hidden"/>
          </a-form-item>
        </row-item>
      </row-list>
      <row-list :col="2">
        <row-item>
          <a-form-item
            label="标题"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['title', {rules: [{required: true, message: '标题不能为空'}]}]"/>
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="目标部门"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-tree-select
              style="width: 100%"
              :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
              :treeData="treeData"
              :treeNodeFilterProp="'title'"
              :showSearch="true"
              treeDefaultExpandAll
              :replaceFields="{value: 'id'}"
              v-decorator="['targetDept', {rules: [{required: true, message: '目标部门不能为空'}]}]"
              placeholder="请选择"
            >
            </a-tree-select>
          </a-form-item>
        </row-item>
      </row-list>
      <row-list :col="1">
        <row-item>
          <a-form-item
            label="备注"
            :labelCol="BaseTool.Constant.labelCol2"
            :wrapperCol="BaseTool.Constant.wrapperCol2"
          >
            <a-textarea
              :rows="4"
              v-decorator="['remark']"/>
          </a-form-item>
        </row-item>
      </row-list>
    </a-form>

    <a-tabs type="card" default-active-key="1">
      <a-tab-pane key="1" tab="设备列表">
        <div class="table-operator">
          <a-button size="small" type="primary" @click="handleStandardSelect">
            <a-icon type="plus"/>
            添加
          </a-button>
          <a-button class="margin-left8" size="small" type="danger" @click="handleDel">
            <a-icon type="delete"/>
            删除
          </a-button>
        </div>
        <a-table
          bordered
          :data-source="data"
          :columns="columns"
          tableLayout="auto"
          rowKey="id"
          :scroll="{ x: 1600, y: BaseTool.Constant.scrollY }"
          :row-selection="rowSelection"
        >
          <span slot="action" slot-scope="record">
            <template>
              <a @click="handleView(record)">查看</a>
            </template>
          </span>
          <span slot="status" slot-scope="text">
            <badge :status="DictCache.COLOR.SB_INFO_STATUS[text]" :text="statusMap[text]" />
          </span>
        </a-table>
      </a-tab-pane>
    </a-tabs>
    <sb-info-select-modal-by-user ref="sbInfoSelectModalByUser" :type="'checkbox'" @selected="handleSbSelected"/>
    <detail ref="detailModal"/>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
    </template>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import SbInfoSelectModalByUser from '@/views/sb/info/modules/SbInfoSelectModalByFilter'
import Detail from '@/views/sb/info/modules/Detail'
import { addSbAllocateApply, updateSbAllocateApply } from '@/api/sb/allocate-apply'
import { fetchSbInfo } from '@/api/sb/info'
import { getDeptAllocateTree } from '@/api/upms/dept'

export default {
  name: 'BaseSbAllocateApply',
  components: {
    SbInfoSelectModalByUser,
    Detail
  },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      levelMap: {},
      statusMap: {},
      type: null,
      rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
        }
      },
      treeData: [],
      // 表头
      columns: [
        {
          title: '设备编号',
          dataIndex: 'no',
          width: 200
        },
        {
          title: '设备名称',
          dataIndex: 'name',
          width: 200
        },
        {
          title: '设备类型',
          dataIndex: 'type',
          width: 200,
          customRender: (text, record, index) => {
            return record.typeName
          }
        },
        {
          title: '设备等级',
          dataIndex: 'level',
          width: 200,
          customRender: (text, record, index) => {
            return this.BaseTool.Object.getField(this.levelMap, text)
          }
        },
        {
          title: '生产商',
          dataIndex: 'producerId',
          width: 200,
          customRender: (text, record, index) => {
            return record.producerName
          }
        },
        {
          title: '规格型号',
          dataIndex: 'guigeId',
          width: 200,
          customRender: (text, record, index) => {
            return record.guigeName
          }
        },
        {
          title: '状态',
          dataIndex: 'status',
          width: 200,
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '操作',
          key: 'action',
          width: '200px',
          align: 'center',
          fixed: 'right',
          scopedSlots: { width: 200, customRender: 'action' }
        }
      ],
      data: [],
      selectedRowKeys: [],
      selectedRows: [],
      options: {
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys
        }
      },
      // 下拉框map
      typeMap: {}
    }
  },
  props: {},
  created () {
    // 下拉框map
    this.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SB_ALLOCATE_APPLY_TYPE)
    this.statusMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SB_INFO_STATUS)
    this.levelMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SBINFO_LEVEL)
  },
  methods: {
    base (record, type) {
      this.visible = true
      this.type = type
      this.getDeptAllocateTree()
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.modalTitle = '添加'
        return
      }
      this.modalTitle = '编辑'
      const { form: { setFieldsValue } } = this
      // 日期处理
      record.startTime = this.BaseTool.Moment(record.startTime, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
      record.endTime = this.BaseTool.Moment(record.endTime, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
      this.data = record.sbInfos !== null ? record.sbInfos : []
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'title',
          'targetDept',
          'remark'
        ])))
      })
    },
    getDeptAllocateTree () {
      getDeptAllocateTree({ allocateType: this.type }).then(res => {
        this.treeData = res.data
      })
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        if (this.data == null || this.data.length === 0) {
          this.$message.error('请选择设备')
          return
        }
        // 日期处理
        values.sbInfos = this.data
        values.type = this.type
        if (this.BaseTool.String.isBlank(values.id)) {
          addSbAllocateApply(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updateSbAllocateApply(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleStandardSelect () {
      this.$refs.sbInfoSelectModalByUser.base({ notStatusList: [this.DictCache.VALUE.SB_INFO_STATUS.IN_DIAOBO] })
    },
    handleDel () {
      const data = [...this.data]
      if (this.selectedRowKeys.length === 0) {
        this.$message.error('请至少选择一条数据')
        return
      }
      this.data = data.filter(item => !this.selectedRowKeys.includes(item.id))
    },
    handleSbSelected (keys, rows) {
      const { data } = this
      const len = data.length
      for (let i = 0; i < rows.length; i++) {
        const row = rows[i]
        let flag = false
        for (let j = 0; j < len; j++) {
          if (row.id === data[j].id) {
            flag = true
          }
        }
        if (!flag) {
          data.push(row)
        }
      }
    },
    handleView (record) {
      fetchSbInfo({ id: record.id }).then(res => {
        const modal = this.$refs.detailModal
        modal.base(res.data)
      })
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      this.data = []
      if (this.BaseTool.Object.isNotBlank(values)) {
        this.$emit('ok', values)
      }
    }

  }
}
</script>
